package net.expectx.common.single.util;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
 * @author lijian
 */
public class CreateFileUtil {
    private static final String A=",";

    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + fileName + ".json";

        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            /**
             * 如果父目录不存在，创建父目录
             */
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            /**
             * 如果已存在,删除旧文件
             */
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

            // 格式化json字符串
            jsonString = JsonFormatTool.formatJson(jsonString);

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        // 返回是否成功的标记
        return flag;
    }
    public static boolean deleteFile(String srcFileName,Boolean deleteAll,String suffix){
        if(StringUtils.isEmpty(srcFileName)){
            return false;
        }
        try {
            File file=new File(srcFileName);
            File[] files = new File[0];
            if(file.isDirectory()) {
                files = file.listFiles();
                for(int i=0;i<files.length;i++){
                    File f=new File(srcFileName+files[i].getName());
                    if (deleteAll){
                        System.out.println(f.delete());
                    }else{
                        if (null!=suffix){
                            for (String suff:suffix.split(A)){
                                if (f.getName().contains(suff)){
                                    System.out.println(f.delete());
                                }
                            }
                        }else{
                            System.out.println(f.delete());
                        }
                    }

                }
            }else {
                System.out.println(srcFileName);
                new File(srcFileName).delete();
            }
            return true;
        }
        catch (Exception e) {
            System.out.println("文件删除出错");
            return false;
        }
    }

}
